<template>
  <div>
    <!-- 搜索查询 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model="formInline.name"
          placeholder="请输入姓名查询"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="find">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="port">导出选中数据</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addMany">批量添加数据</el-button>
      </el-form-item>
    <!-- 新增学生家庭信息 -->
      <el-form-item>
        <el-button type="success" @click="addFamilyInfo(form)">新增学生家庭信息</el-button>
      </el-form-item>
    </el-form>
      
    <!-- 新增数据弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="添加学生家庭信息">
      <el-form :model="formData" ref="form" :rules="rules">
        <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="formData.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="父亲" prop="father" :label-width="formLabelWidth">
          <el-input v-model="formData.father" autocomplete="off" />
        </el-form-item> 
        <el-form-item label="母亲" prop="mother" :label-width="formLabelWidth">
          <el-input v-model="formData.mother" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系电话" prop="Telephone" :label-width="formLabelWidth">
          <el-input v-model="formData.Telephone" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="家庭住址"
          prop="address"
          :label-width="formLabelWidth"
          v-model="formData.address"
        >
          <el-cascader
            size="large"
            :options="optionsArea"
            v-model="selectedOptions"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="sure(form)"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
  <!-- table表格 -->
  <el-table
      :data="data.tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
      border
      style="width: 100%"
      @selection-change="selectionChange"
    >
     <el-table-column type="selection" align="center">
     </el-table-column>
      <el-table-column prop="name" label="姓名" align="center" />
      <el-table-column prop="father" label="父亲" align="center" />
      <el-table-column prop="mother" label="母亲" align="center" />
      <el-table-column prop="Telephone" label="联系电话" align="center" />
      <el-table-column prop="address" label="家庭住址" align="center" />
      <el-table-column prop="操作" label="操作" align="center">
        <template #default="scope">
          <!-- scope.row可以获取当前item中的所有数据 -->
          <el-button type="primary" round @click="edit(scope.row)"> 
            <Edit style="width: 1.2em; height: 1.2em; margin-right: 0" />
           </el-button>
          <el-popconfirm title="确定要删除该生的家庭信息？" @confirm="delInfo(scope.row)" confirm-button-type="danger">
            <template  #reference>
              <el-button type="danger" round>
                <Delete style="width: 1.2em; height: 1.2em; margin-right: 0" />
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
   <!-- 编辑学生家庭信息对话框 -->
   <el-dialog title="编辑" v-model="popShow" center>
      <el-form :model="editData" ref="ruleFormRef" :rules="rules">
        <el-form-item label="ID" prop="id" required v-if="false">
          <el-input v-model="editData.id" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名" prop="name" required>
          <el-input v-model="editData.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="父亲" prop="father">
          <el-input v-model="editData.father" autocomplete="off" />
        </el-form-item>
        <el-form-item label="母亲" prop="mother">
          <el-input v-model="editData.mother" autocomplete="off" />
        </el-form-item>
        <el-form-item label="联系电话" prop="Telephone" required>
          <el-input v-model="editData.Telephone" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="家庭住址"
          prop="address"
          :label-width="formLabelWidth"
          v-model="editData.address"
        >
          <el-cascader
            size="large"
            :options="optionsArea"
            v-model="selectedOptions"
            @change="handleChange"
          >
          </el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button @click="popShow=false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  <div class="pagination">
  <!-- 分页 -->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15,20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
  <!-- <Edit
    :popShow="popShow"
    v-if="popShow"
    :message="familyItemState.message"
    :confirmClick="confirmClick"
  ></Edit> -->
  
</template>

<script setup>
import router from '@/router/index'
import xlsx from "xlsx";
import {  onMounted, reactive, ref } from "vue";
import { ElMessage,ElLoading } from "element-plus";

// 引入学生家庭信息列表查询接口方法
import { familyInfo,familyInfoFind,updateFamilyInfo,delFamilyInfo,addFamilyInfos} from '../../../api/api'
// regionDataPlus是省市区三级联动数据（带“全部”选项）
// CodeToText是个大对象，属性是区域码，属性值是汉字 用法例如：CodeToText['110000']输出北京市
import { regionDataPlus, CodeToText } from "element-china-area-data";
const optionsArea = regionDataPlus;
const selectedOptions = ref([]);
// 定义选中的数据
let selectionList = reactive({
  data:[]
})
// 拿到所有选中的数据赋值给selectionList
const selectionChange = (val)=>{
  selectionList.data = val
}
// 导出数据
const port = ()=>{
  // 如果没有选中数据
  if(selectionList.data.length <= 0){
    ElMessage({
      message:'请先选择要导出的数据！',
      type:'warning'
    })
    return;
  }
  // 加载
  const loadingInstance = ElLoading.service({
    text:'稍等正在处理！',
    background:'rgba(0,0,0,.5)'
  })
  // 最终要导出数据的格式
  let arr = selectionList.data.map(item=>{
    return {
      姓名:item.name,
      父亲:item.father,
      母亲:item.mother,
      联系电话:item.Telephone,
      家庭住址:item.address
    }
  })
  let sheet = xlsx.utils.json_to_sheet(arr)//把json数据变成sheet数据
  let book = xlsx.utils.book_new()//新建一个表格
  xlsx.utils.book_append_sheet(book,sheet,'sheet1')//往当前表格插入一个sheet1的列，数据是sheet
  xlsx.writeFile(book, `user${new Date().getTime()}.xls`);//写入文件
  loadingInstance.close()
}
// 路由跳转
const addMany = ()=>{
  router.push("/home/familyInfo/UploadFamily")
}
// 模拟数据
//  const data = reactive({  
//   list: [
//     {
//       id: 1,
//       name: "张三",
//       father: "张三爸爸",
//       mother: "张三妈妈",
//       Telephone: "11111111111",
//       address: "北京市 通州",
//       del: "1",
//     },
//     {
//       id: 2,
//       name: "李四",
//       father: "李四爸爸",
//       mother: "李四妈妈",
//       Telephone: "18726378765",
//       address: "天津市南开区",
//       del: "0",
//     },
//     {
//       id: 2,
//       name: "王五",
//       father: "王五爸爸",
//       mother: "王五妈妈",
//       Telephone: "18726378765",
//       address: "天津市南开区",
//       del: "0",
//     },
    
    
//   ],
// });
// 获取数据
let data = reactive({
  tableData:[]
})
// 选择地区
const handleChange = () => {
  console.log(selectedOptions.value);
  if (selectedOptions.value[0] != null && selectedOptions.value[1] != null) {
    const str =
      CodeToText[selectedOptions.value[0]] +
      CodeToText[selectedOptions.value[1]] +
      CodeToText[selectedOptions.value[2]];
    console.log(str);
    formData.address = str;
    editData.address = str;
  }
};
// 根据名字查询
const formInline = reactive({
  name:''
})
// 定义编辑的数据
let popShow = ref(false)
let ruleFormRef = ref(null)
const editData = reactive({
  name:'',
  father:'',
  mother:'',
  Telephone:'',
  address:'',
    id:''
})
// 定义分页的数据
let currentPage = ref(1)//当前页数
let pageSize = ref(5);//每页显示条数
let total = ref(0)//总条数(实际总条数是从接口获取的)
// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  console.log(`每页 ${val} 条`);
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  console.log(`当前页： ${val} 条`)
};
// 获取数据(模拟数据)
onMounted(() =>{
  familyInfoData();
})
//学生家庭信息列表数据的获取
const familyInfoData = async(params) =>{
  await familyInfo(params).then((res) =>{
    console.log(res)
    if (res.data.code === 0) {
      data.tableData = res.data.data.list;
      console.log('数据')
      total.value = res.data.data.total;
    }
  });
}
/**
 * 新增学生家庭信息
 */
let dialogFormVisible = ref(false)//新增弹窗显示/隐藏
const formLabelWidth = '90px'
const formData = reactive({
  name:'',
  father:'',
  mother:'',
  Telephone:'',
  address:''
})
// 新增数据表单验证
const rules = {
  name: [{ required: true, message: "请输入学生姓名" }],
  father:[{}],
  mother:[{}],
  Telephone: [{ required: true,pattern:(/^1[3-9]\d{9}$/),message: "请输入正确的11位手机号" }],
  address: [{required: true, }],
}
//新增功能
const addFamilyInfo = (form) =>{
  console.log(form)
  dialogFormVisible.value = true
  form.resetFields()//重置表单
}
// 添加数据确定按钮
let form = ref(null)
let sure = async (form) => {
  await form.validate((valid) => {
    if (valid) {
      console.log("新增数据", formData);
      addFamilyInfos(formData).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          familyInfoData();
          ElMessage({
            type: "success",
            message: res.data.message,
          });
          dialogFormVisible.value = false; //关闭弹框
        }
      });
    }
  });
};


/**
 * 查询功能
 */
 const find = async () => {
  console.log(formInline)
  await familyInfoFind(formInline).then((res) => {
    console.log(res);
    if (res.data.code === 0) {
      // familyInfoData()
      data.tableData = res.data.data.list;
      total.value = res.data.data.total;
      if(formInline.name){
        ElMessage({
          message: "查询成功",
          type: "success",
        })
      }else{
        
        ElMessage({
          message: "请输入要查询的内容",
          type: "warning",
        })
      }
    }
    
  });
};
// 重置
const reset = ()=>{
  familyInfoData()
}

// 编辑方法
const edit = (row)=>{
  console.log('编辑',row)
  popShow.value = true//显示对话框
  editData.id = row.id//传值
  editData.name = row.name
  editData.father = row.father
  editData.mother = row.mother
  editData.Telephone = row.Telephone
  editData.address = row.address
  console.log('赋值',editData)
}
// 编辑数据确定按钮
let submitForm = async (ruleFormRef) => {
  await ruleFormRef.validate((valid) => {
    if (valid) {
      console.log("编辑数据",editData);
      updateFamilyInfo(editData).then((res) => {
        console.log(editData)
        console.log('@@')
        console.log(res)
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.message,
          });
          familyInfoData()
          popShow.value = false; //关闭弹框
          
        }
      });
    }
  });
};
// 搜索逻辑
// const famliyList = computed(() => {
//   return data.tableData?.filter((item) => {
//     return item.name.indexOf(inputValue.value) >= 0;
//   });
// });
// // 搜索按钮方法
// const search = () => {
//   if (inputValue.value) {
//     ElMessage({
//       message: "查询成功",
//       type: "success",
//     });
//   } else {
//     ElMessage({
//       message: "请输入要查询的内容",
//       type: "warning",
//     });
//   }
// };


/**
 * 删除学生家庭信息功能
 */
 let delInfo = (row) => {
  console.log(row);
  delFamilyInfo(row.id).then((res) => {
    console.log('@',res);
    if (res.data.code === 0) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      // 删除成功后重新渲染数据
      familyInfoData();
    }
  });
};
</script>

<style lang="less" scoped>
</style>
